package cn.tj212.xiaoyin.wechat.wxapi.process;

import cn.tj212.xiaoyin.wechat.wxapi.vo.MsgRequest;
import cn.tj212.xiaoyin.wechat.wxapi.vo.MsgResponseNews;
import cn.tj212.xiaoyin.wechat.wxapi.vo.MsgResponseText;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * xml 消息处理工具类
 */
public class MsgXmlUtil {
    public static String newsToXml(MsgResponseNews msgResponseNews) {
    }

    /**
     * 将request消息转换为请求消息对象
     *
     * @param request
     * @return
     */
    public static MsgRequest parseXml(HttpServletRequest request) throws Exception {
        MsgRequest msgReq = new MsgRequest();

        //解析xml
        InputStream inputStream = request.getInputStream();

        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();

        //遍历节点封装成对象
        for (Element e : elementList
        ) {
            String name = e.getName();
            String text = e.getText();
            if ("MsgType".equals(name)){
                msgReq.setMsgType(text);
            }else if ("MsgId".equals(name)){
                msgReq.setMsgId(text);
            }else if ("FromUserName".equals(name)){
                msgReq.setFromUsername(name);
            }else if ("ToUserName".equals(name)){
                msgReq.setToUsername(text);
            }else if ("CreateTime".equals(name)){
                msgReq.setCreateTime(text);
            }else if ("Content".equals(name)){
                msgReq.setContent(text);
            }else if ("PicUrl".equals(name)){
                msgReq.setPicUrl(text);
            }else if ("Location_X".equals(name)){
                msgReq.setLocation_X(text);
            }else if ("Location_Y".equals(name)){
                msgReq.setLocation_Y(text);
            }else if("Scale".equals(name)){
                msgReq.setScale(text);
            }else if("Label".equals(name)){
                msgReq.setLabel(text);
            }else if("Event".equals(name)){//事件消息
                msgReq.setEvent(text);
            }else if("EventKey".equals(name)){
                msgReq.setEventKey(text);
            }
        }
        inputStream.close();
        inputStream=null;
        return msgReq;
    }

    public static String textToXml(MsgResponseText text){

    }
}
